//
//  UpDatePowerVersonViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/10.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "UpDatePowerVersonViewController.h"
#import "UIImage+GIF.h"
#import "BorderHelper.h"


@interface UpDatePowerVersonViewController ()
{
    NSInteger _type;
    NSInteger _buttonType;
}
@end

@implementation UpDatePowerVersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self UISetting];
}

- (void)UISetting{
    [BorderHelper setBorderWithColor:kGreenColor button:_buttonUpdate];
    [_buttonUpdate setTitleColor:kGreenColor forState:UIControlStateNormal];
    
    [BorderHelper setBorderWithColor:kWhiteColor button:_buttonCheckVerson];
    [_buttonCheckVerson setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_buttonCheckVerson setBackgroundColor:kGreenColor];

}

//设置imageViewLoading图片
- (void)showLoadingImage:(UIImageView *)imageView{
    imageView.image = [UIImage imageNamed:@"dengdai"];
}

//设置imageView成功后的图片
- (void)showSuccessImage:(UIImageView *)imageView{
    imageView.image = [UIImage imageNamed:@"wancheng"];
}

//显示gif图
- (void)showGifImage:(UIImageView *)imageView{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"zhuan-ing" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage sd_animatedGIFWithData:data];
    imageView.image = image;
}

//失败时显示图片
- (void)showFaultImage:(UIImageView *)imageView{
    imageView.image = [UIImage imageNamed:@"shibai"];
    [self.hub hideAnimated:YES];
}

//重置图片
- (void)reloadImage{
    [self showLoadingImage:_imageView1];
    [self showLoadingImage:_imageView2];
    [self showLoadingImage:_imageView3];
    [self showLoadingImage:_imageView5];
    [self showLoadingImage:_imageView6];
    [self showLoadingImage:_imageView9];
}

#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//更新设备
- (IBAction)updateButtonClick:(UIButton *)sender {
    [self reloadImage];
    
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _type = 0;
    _buttonType = 1;
    [self searchPowerFunc];
}

//检测版本
- (IBAction)checkButtonClick:(UIButton *)sender {
    [self reloadImage];

    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _type = 0;
    _buttonType = 2;
    [self searchPowerFunc];
}

#pragma mark - 更新固件逻辑

//查找充电宝
- (void)searchPowerFunc{
    
    if (_type == 0) {//第一次
        //第一张 给我转
        [self showGifImage:_imageView1];
    }else{
        [self showGifImage:_imageView5];
    }
    
    [[AFClient shareInstance] findPowerByEid:kUserId alias:_powerId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            //查找充电宝动作完成
            if (_type == 0) {//第一张 给我成功
                [self showSuccessImage:_imageView1];
            }else{
                [self showSuccessImage:_imageView5];
            }
            
            NSDictionary *dataDic = responseBody[@"data"];
            
            PowerModel *model = [[PowerModel alloc] init];
            NSDictionary *chargingDic = dataDic[@"charging"];
            if ([chargingDic class] != [NSNull class]) {
                [model setValuesForKeysWithDictionary:chargingDic];
            }
            
            ShopModel *shopModel = [[ShopModel alloc] init];
            NSDictionary *shopDic = dataDic[@"store"];
            if ([shopDic class] != [NSNull class]) {
                [shopModel setValuesForKeysWithDictionary:shopDic];
            }
            NSString *verson = kPowerVerson;
            
            //拿到版本号后，对版本进行对比
            if (_type == 0) {
                //第二张 差不多要开始转啦
                [self showGifImage:_imageView2];
            }else{
                [self showGifImage:_imageView6];
            }
            if (model.firmware_version.integerValue < verson.integerValue) {//如果充电宝版本小于服务器版本，准备更新
                //版本对比完毕，第二张达到条件达到条件
                
                if (_type == 0) {//第一次执行
                    [self showSuccessImage:_imageView2];
                    
                    //调用 —> 指令：查询固件
                    
                    [self showGifImage:_imageView3];
                    [self findPowerNotiFunc];
                }else{//第二次执行

                    if (_buttonType == 2) {//检测版本
                        [self.hub hideAnimated:YES];
                        [self showLoadingImage:_imageView6];
                        [self alertVCByTitle:[NSString stringWithFormat:@"\n当前版本号：%@\n\n最新版本号：%@",model.firmware_version,kPowerVerson]];
                    }else{
                        [self updatePowerFunc];
                    }
                }
            }else{
                if (_type == 0) {//第一次失败
                    [self showFaultImage:_imageView2];
                }else{//第二次失败
                    [self showFaultImage:_imageView6];
                }
                
                [self alertVCByTitle:@"该设备已是最新版本无需更新"];
            }
            
        }else{
            if (_type == 0) {//第一张 给我成功
                [self showFaultImage:_imageView1];
            }else{
                [self showFaultImage:_imageView5];
            }
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        if (_type == 0) {//第一张 给我成功
            [self showFaultImage:_imageView1];
        }else{
            [self showFaultImage:_imageView5];
        }
    }];
}
//指令，查找充电宝
- (void)findPowerNotiFunc{
    
    [[AFClient shareInstance] findPowerNotiByPowerByEid:kUserId alias:_powerId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {//拿到messageId后等待两秒，调用检查链路等待消息返回
            //调用指令，查找充电宝，并返回成功，第三步完成
            
            
            NSString *messageId = responseBody[@"data"];
            __block UpDatePowerVersonViewController*weakSelf = self;
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                
//                [weakSelf checkLinkByMessageId:messageId];
                [weakSelf showSuccessImage:_imageView3];
                _type = 1;
                [weakSelf searchPowerFunc];
            });

        }else{
            [self showFaultImage:_imageView3];
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self showFaultImage:_imageView3];
    }];
}


//检查链路
- (void)checkLinkByMessageId:(NSString *)messageId{
    NSLog(@"messageId -> %@",messageId);
    [[AFClient shareInstance] checkPostToPowerByMessage_id:messageId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            //检查链路，消息已发送， 后台拿到充电宝硬件信息，重新调查找充电宝接口
            if (_type == 0) {//第一次检查链路 -》查找充电宝
                [self showSuccessImage:_imageView3];
                _type = 1;
                [self searchPowerFunc];
            }else{//第二次检查链路 -》更新固件
                //（等待15秒）本地提示 —>固件正在更新，请耐心等待
                __block UpDatePowerVersonViewController*weakSelf = self;
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(25.0/*延迟执行时间*/ * NSEC_PER_SEC));
                
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    
                    //更新完成
                    [weakSelf alertVCByTitle:@"更新完成"];
                    
                });
            }
            
        }else{
            if (_type == 0) {
                [self showFaultImage:_imageView3];
            }else{
                [self showFaultImage:_imageView9];
            }
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        if (_type == 0) {
            [self showFaultImage:_imageView3];
        }else{
            [self showFaultImage:_imageView9];
        }
    }];
}


//更新固件
- (void)updatePowerFunc{
    [[AFClient shareInstance] updatePowerVersonByEid:kUserId alias:_powerId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {//拿到messageId后等待两秒，调用检查链路等待消息返回
            [self showSuccessImage:_imageView6];
            NSString *messageId = responseBody[@"data"];
            [self showGifImage:_imageView9];
            __block UpDatePowerVersonViewController*weakSelf = self;
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30.0/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [weakSelf.hub hideAnimated:YES];
                [weakSelf showSuccessImage:_imageView9];
                [weakSelf alertVCByTitle:@"升级指令已发送稍等片刻后，\n请点击[检测版本]，查询是否升级成功"];
//                [weakSelf checkLinkByMessageId:messageId];
            });
            
        }else{
            [self showFaultImage:_imageView6];
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self showFaultImage:_imageView6];
    }];
}

- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
